<?php

class BotCommand extends CConsoleCommand {
		
	public $client;	
	public function init()
	{
	
			require_once(YII::getPathOfAlias("application.extensions.jabber.jaxl.Jaxl" ) . '.php');
        	require_once(YII::getPathOfAlias("application.extensions.jabber.jaxl.core.jaxl_socket_client" ) . '.php');
        	require_once(YII::getPathOfAlias("application.extensions.jabber.jaxl.xmpp.xmpp_jid" ) . '.php');
		
		$this->client = new Jaxl ( array (// (required) credentials
		'jid' => YII::app ()->params ['accounts']['jabber'] ['bot_component'] ['jid'], 
		'pass' => YII::app ()->params ['accounts']['jabber'] ['bot_component'] ['password'],
		'host' => YII::app ()->params ['accounts']['jabber'] ['bot_component'] ['host'],
		'port' => YII::app ()->params ['accounts']['jabber'] ['bot_component'] ['port'],
		
		// 'strict' => false ,
		//'force_tls' => true,
		'log_level' => JAXL_INFO,
		));
		
	$this->client->require_xep(array('0114'));
	}
    public function actionIndex()
	{
	
	$client = $this->client;
	
	$this->client->add_cb('on_auth_failure', function($reason)use($client) {
		$client->send_end_stream();
	 	_info("got on_auth_failure cb with reason $reason");
	});
		 
		
	$this->client->add_cb ( 'on_auth_success', function () use ($client) {

			$client->set_status ( "available!" ); // set your status
			_info("got on_auth_success");
		} );
		
		$this->client->add_cb ( 'on_chat_message', function ($msg) use($client) {
			$msg->to = $msg->from;
			$msg->from = $client->jid->to_string ();
			$client->send ( $msg );
				_info("got on_chat_message");
		} );
		
		$this->client->add_cb ( 'on_disconnect', function () {
			_debug ( "got on_disconnect cb" );
		} );

		$this->client->start();
        	
	}
	public function actionSendMessage()
	{
	$client = $this->client;
	
	$this->client->add_cb('on_auth_failure', function($reason)use($client) {
		$client->send_end_stream();
	 	_info("got on_auth_failure cb with reason $reason");
	});
		 
		
	$this->client->add_cb ( 'on_auth_success', function () use ($client) {

			$client->set_status ( "available!" ); // set your status

			$msg = new XMPPMsg(
			array(
				'type'=>'chat', 
				'to'=>'admin@neocasta.com', 
				'from'=>$client->jid->to_string()
			), 
			'test',
			$thread=null,
			$subject=null
			);
		$client->send($msg);
			
		
		_info("got on_auth_success");
			$client->send_end_stream();

			
		} );
		
		$this->client->add_cb ( 'on_chat_message', function ($msg) use($client) {
			$msg->to = $msg->from;
			$msg->from = $client->jid->to_string ();
			$client->send ( $msg );
				_info("got on_chat_message");
		} );
		
		$this->client->add_cb ( 'on_disconnect', function () {
			_debug ( "got on_disconnect cb" );
		} );
		$this->client->start();
	}
	
}
